package com.xoa.controller.diary;


import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.zip.DataFormatException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xoa.model.diary.DiaryCommentModel;
import com.xoa.model.diary.DiaryCommentReplyModel;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.xoa.controller.file.FileController;
import com.xoa.model.diary.DiaryModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.service.diary.DiaryService;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import com.xoa.util.treeUtil.HtmlUtil;

@Controller
@RequestMapping("/diary")
public class DiaryController {
    private Logger loger = Logger.getLogger(DiaryController.class);
    @Resource
    DiaryService diaryService;

    @Resource
    SmsService smsService;

    @RequestMapping("/workLog")
    public String workLog() {
        return "app/diary/workLog";
    }

    //H5微应用
    //日志
    @RequestMapping("/diaryIndexh5")
    public String diaryIndex() {
        return "/app/diary/m/indexh5";
    }
    //我发起的
    @RequestMapping("/iStartedListh5")
    public String iStartedList() {
        return "/app/diary/m/iStarted_listh5";
    }
    //新建
    @RequestMapping("/diaryCreateh5")
    public String diaryCreate() {
        return "/app/diary/m/Createh5";
    }
    //详情
    @RequestMapping("/diaryConsulth5")
    public String diaryConsult() {
        return "/app/diary/m/consulth5";
    }
    //点评
    @RequestMapping("/diaryCommenth5")
    public String diaryComment() {
        return "/app/diary/m/commenth5";
    }
    //分享我的列表页
    @RequestMapping("/diaryShareListh5")
    public String diaryShareList() {
        return "/app/diary/m/share_listh5";
    }
    //分享我的详情页
    @RequestMapping("/diaryReceivedDetailsh5")
    public String diaryReceivedDetails() {
        return "/app/diary/m/received_detailsh5";
    }
    //统计首页
    @RequestMapping("/diaryCounth5")
    public String diaryCount() {
        return "/app/diary/m/counth5";
    }
    //统计列表页
    @RequestMapping("/diaryCountListh5")
    public String diaryCountList() {
        return "/app/diary/m/count_listh5";
    }
    //日期显示页
    @RequestMapping("/diaryCalenderh5")
    public String diaryCalender() {
        return "/app/diary/m/calenderh5";
    }


    @RequestMapping("/details")
    public String details(HttpServletRequest request,String ID,String bodyId) {
        String visitUrl= request.getRequestURI();
        visitUrl+="?ID="+ID;
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        smsService.setRead(request,visitUrl);
        return "app/diary/details";
    }


    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-24 下午2:39:25
     * 方法介绍:   跳转主页面
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return String
     */
    @RequestMapping("/index")
    public String diaryIndex(DiaryModel diaryModel, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        //消除事务提醒
        String diaId=request.getParameter("diaId");
        if(!StringUtils.checkNull(diaId)){
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            smsService.setSmsRead("13","/diary/index?diaId="+diaId,users);
        }
        return "app/diary/index";
    }

    /**
     * @Author 廉立深
     * @Description 优化工作日志
     * @Date 11:03 2020/5/20
     * @Param [request, diaryModel]
     * @return com.xoa.util.ToJson<com.xoa.model.diary.DiaryModel>
     **/
    @RequestMapping("/findDiaryGet")
    @ResponseBody
    public ToJson<DiaryModel> findDiaryGet( HttpServletRequest request,
                                            DiaryModel diaryModel,
                                            @RequestParam("type") String type,
                                            Integer page,@RequestParam(value = "pageSize", required=false)Integer limit) {
        return diaryService.findDiaryGet(request,diaryModel,type,page,limit);
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午4:00:13
     * 方法介绍:   工作日志添加控制层
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public ToJson<DiaryModel> diaryAdd(DiaryModel diaryModel, HttpServletRequest request) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>(1,"err");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Date date = new Date();
        diaryModel.setUserId(users.getUserId());
        diaryModel.setDiaDate(DateFormat.getDatestr(date));
        diaryModel.setDiaTime(DateFormat.getStrDate(date));
        int temp = diaryService.saveDiary(diaryModel,request);
        if (temp >= 1 ) {
            json.setFlag(0);
            json.setMsg("true");
        }
        return json;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午4:01:13
     * 方法介绍:   工作日志编辑操作
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public ToJson<DiaryModel> diaryUpdate(DiaryModel diaryModel, HttpServletRequest request) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>(1,"err");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        int temp = diaryService.updateDiary(diaryModel,request);
        if (temp >= 1) {
            json.setFlag(0);
            json.setMsg("修改成功！");
        }
        return json;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午4:34:11
     * 方法介绍:   动态查询日志操作
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel> 自己的日志内容
     */
    @RequestMapping(value = "/getIndex", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<DiaryModel> diaryGet(DiaryModel diaryModel, HttpServletRequest request,
                                       @RequestParam("page") Integer page,
                                       @RequestParam("pageSize") Integer pageSize,
                                       @RequestParam("useFlag") Boolean useFlag) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Users users= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        diaryModel.setUserId(users.getUserId());

        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        ToJson<DiaryModel> diaryToJson = diaryService.getDiaryIndex(diaryModel, pageParams,request);
        return diaryToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-20 上午9:16:19
     * 方法介绍:   取得全部共享
     * 参数说明:   @param diaryModel
     *
     * @return void
     */
    @RequestMapping("/getAll")
    @ResponseBody
    public ToJson<DiaryModel> diaryGetAll(DiaryModel diaryModel, HttpServletResponse response, HttpServletRequest request,
                                          @RequestParam("page") Integer page,
                                          @RequestParam("pageSize") Integer pageSize,
                                          @RequestParam("useFlag") Boolean useFlag) {
        ContextHolder.setConsumerType("xoa" + (String) request.getSession().getAttribute("loginDateSouse"));
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        if (diaryModel.getUserId() == null || "".equals(diaryModel.getUserId())) {
            HttpSession session = request.getSession();
            diaryModel.setUserId(session.getAttribute("userId").toString());
        }
        ToJson<DiaryModel> diaryToJson = diaryService.getDiaryAll(diaryModel, pageParams,request);
        return diaryToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-24 下午2:38:34
     * 方法介绍:   取得他人共享
     * 参数说明:   @param diaryModel
     * 参数说明:   @param response
     * 参数说明:   @return
     *
     * @return String
     */
    @RequestMapping(value = "/getOther", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<DiaryModel> diaryGetOther(DiaryModel diaryModel, HttpServletRequest request,
                                            @RequestParam("page") Integer page,
                                            @RequestParam("pageSize") Integer pageSize,
                                            @RequestParam("useFlag") Boolean useFlag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);

        if (diaryModel.getUserId() == null || "".equals(diaryModel.getUserId())) {
            HttpSession session = request.getSession();
            diaryModel.setUserId(session.getAttribute("userId").toString());
        }
        ToJson<DiaryModel> diaryOtherToJson = diaryService.getDiaryOther(diaryModel, pageParams,request);
        return diaryOtherToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-3 下午2:12:36
     * 方法介绍:   通过id获取详情
     * 参数说明:   @param diaryModel
     * 参数说明:   @param request
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>
     */
    @RequestMapping(value = "/getConByDiaId", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<Attachment> getConByDiaId(DiaryModel diaryModel, HttpServletRequest request) {
        String sqlType = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
        ContextHolder.setConsumerType(sqlType);
        if (diaryModel.getUserId() == null || "".equals(diaryModel.getUserId())) {
            HttpSession session = request.getSession();
            diaryModel.setUserId(session.getAttribute("userId").toString());
        }
        ToJson<Attachment> diaryOtherToJson = diaryService.getDiaryByDiaId(diaryModel, sqlType);
        return diaryOtherToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-8 上午9:55:01
     * 方法介绍:   通过日志ID删除一条日志信息
     * 参数说明:   @param diaryModel
     * 参数说明:   @param request
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>  删除日志信息
     */
    @RequestMapping(value = "/delete", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<DiaryModel> deletDiaById(DiaryModel diaryModel, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<DiaryModel> diaryResult = new ToJson<DiaryModel>();
        if (diaryModel.getDiaId() == null || "".equals(diaryModel.getDiaId())) {
            diaryResult.setMsg("删除失败");
            return diaryResult;
        }
        int i = diaryService.deletDiaById(diaryModel);
        if (i == 0) {
            diaryResult.setMsg("无该条记录");
            return diaryResult;
        }
        diaryResult.setFlag(0);
        diaryResult.setMsg(i + "");
        return diaryResult;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-12 上午11:11:47
     * 方法介绍:   工作日志模块高级查询请求调用
     * 参数说明:   @param diaryModel
     * 参数说明:   @param request 请求获取参数通过map获取 在程序中有注释
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>
     */
    @RequestMapping(value = "/diarySelect", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<DiaryModel> diarySelect(DiaryModel diaryModel, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<DiaryModel> diaryResult = new ToJson<DiaryModel>();
        Map<String, String> mapParamter = new HashMap<String, String>();
        @SuppressWarnings("unchecked")
        Map<String, String[]> paramMap = request.getParameterMap();

        Iterator<String> iKeys = paramMap.keySet().iterator();
        while (iKeys.hasNext()) {
            String key = iKeys.next();
            String[] value = paramMap.get(key);
            if (value != null && value.length > 0) {
                mapParamter.put(key, value[0]);
            } else {
                mapParamter.put(key, "");
            }
        }
        diaryResult = diaryService.diarySelect(mapParamter, request);
        return diaryResult;
    }





    @RequestMapping(value = "/exportDiary", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void exportDiary(DiaryModel diaryModel, HttpServletRequest request, HttpServletResponse response) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<DiaryModel> diaryResult = new ToJson<DiaryModel>();
        Map<String, String> mapParamter = new HashMap<String, String>();
        @SuppressWarnings("unchecked")
        Map<String, String[]> paramMap = request.getParameterMap();

        Iterator<String> iKeys = paramMap.keySet().iterator();
        while (iKeys.hasNext()) {
            String key = iKeys.next();
            String[] value = paramMap.get(key);
            if (value != null && value.length > 0) {
                mapParamter.put(key, value[0]);
            } else {
                mapParamter.put(key, "");
            }
        }

         diaryService.exportSelect(mapParamter, request,response);
    }



    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午15:12:05
     * 方法介绍:   添加工作日志评论
     *
     * @return ToJson
     */
    @ResponseBody
    @RequestMapping(value = "/insertDiaryComment", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentModel> insertDiaryComment(DiaryCommentModel diaryCommentModel, HttpServletRequest request) {
        return diaryService.insertDiaryComment(diaryCommentModel, request);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午16:01:29
     * 方法介绍:   获取所有工作日志评论
     *
     * @return ToJson
     */
    @ResponseBody
    @RequestMapping(value = "/getDiaryCommentByDiaId", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentModel> getDiaryCommentByDiaId(String diaId) {
        return diaryService.getDiaryCommentByDiaId(diaId);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午16:54:55
     * 方法介绍:   添加工作日志评论回复
     *
     * @return int 添加条数
     */
    @ResponseBody
    @RequestMapping(value = "/insertCommentReply", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentReplyModel> insertCommentReply(DiaryCommentReplyModel diaryCommentReplyModel, HttpServletRequest request) {
        return diaryService.insertCommentReply(diaryCommentReplyModel, request);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午19:21:00
     * 方法介绍:   根据评论id删除评论
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delDiaryCommentByCommentId", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentModel> delDiaryCommentByCommentId(String commentId) {
        return diaryService.delDiaryCommentByCommentId(commentId);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午19:21:00
     * 方法介绍:   根据评论id删除评论回复
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delCommentReplyByReplyId", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentReplyModel> delCommentReplyByReplyId(String replyId) {
        return diaryService.delCommentReplyByReplyId(replyId);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午10:07:10
     * 方法介绍:   根据日志id查询 评论的数量
     *
     * @return int
     */
    @ResponseBody
    @RequestMapping(value = "/getDiaryCommentCount", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryCommentModel> getDiaryCommentCount(Integer diaId) {
        return diaryService.getDiaryCommentCount(diaId);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午14:14:10
     * 方法介绍:   工作日志置顶
     *
     * @return ToJson
     */
    @ResponseBody
    @RequestMapping(value = "/insertDiaryTop", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryModel> insertDiaryTop(String diaId, HttpServletRequest request) {
        return diaryService.insertDiaryTop(diaId, request);
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午16:10:10
     * 方法介绍:   取消工作日志置顶
     *
     * @return ToJson
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDiaryTop", produces = {"application/json;charset=UTF-8"})
    public ToJson<DiaryModel> deleteDiaryTop(String diaId, HttpServletRequest request) {
        return diaryService.deleteDiaryTop(diaId, request);
    }

    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017-4-19 下午4:34:11
     * 方法介绍:   动态查询日志操作
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel> 自己的日志内容
     */
    @RequestMapping(value = "/PregetIndex", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ToJson<DiaryModel> PregetIndex(DiaryModel diaryModel, HttpServletRequest request,
                                       @RequestParam("page") Integer page,
                                       @RequestParam("pageSize") Integer pageSize,
                                       @RequestParam("useFlag") Boolean useFlag) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        if (diaryModel.getUserId() == null || "".equals(diaryModel.getUserId())) {
            HttpSession session = request.getSession();
            diaryModel.setUserId(session.getAttribute("userId").toString());
        }
        ToJson<DiaryModel> diaryToJson = diaryService.PregetIndex(diaryModel, pageParams,request);
        return diaryToJson;
    }

    /**
     * @作者：张航宁
     * @时间：2017/7/20
     * @介绍：获取浏览人员信息
     * @参数：diaId
     */
    @ResponseBody
    @RequestMapping(value = "/getReaders")
    public ToJson<DiaryModel> getReaders(Integer diaId) {
        return diaryService.getReadUsers(diaId);
    }

    /**
     * @作者：张丽军
     * @时间：2017/7/20
     * @介绍：获取共享人员名称
     * @参数：request
     */
    @ResponseBody
    @RequestMapping(value = "/selectShareName")
    public ToJson<DiaryModel> selectShareName(HttpServletRequest request) {
        return diaryService.selectShareName(request);
    }



}
